
from datetime import datetime
import pandas as pd
from math import *
from vnpy.trader.constant import Exchange, Interval
from vnpy.trader.object import HistoryRequest
from vnpy.trader.rqdata import rqdata_client
from vnpy.trader.database import database_manager
import traceback
if __name__ == "__main__":
    # app = create_qapp()
    symbol = "IF2201"
    exchange = Exchange.CFFEX
    start = datetime(2021, 12, 1)
    end = datetime(2022, 3, 17)
    interval = Interval.MINUTE
    # df_read = pd.read_csv(f'{symbol}.csv', header=0, parse_dates = True, index_col = 'datetime')
    df_read = pd.read_csv(f'{symbol}.csv', header=0,  index_col = 'datetime')
    if not df_read.empty:
        print(df_read.head(3))
        print(type(df_read.index))
    bars = database_manager.load_bar_data(
        symbol, Exchange.CFFEX, interval=Interval.MINUTE, start=start, end=end
    )

    if not bars or len(bars) == 0:
        df = pd.read_csv(f'{symbol}.csv', header=0)
        if df.empty or  len(df) == 0:
            req = HistoryRequest(
                symbol=symbol,
                exchange=exchange,
                interval=Interval.MINUTE,
                start=start,
                end=end,
            )
            try:
                bars = rqdata_client.query_history(req)

                if bars:
                    database_manager.save_bar_data(bars)
                    print(f"{symbol}-{interval}历史数据下载完成")
                else:
                    print(f"数据下载失败，无法获取{symbol}的历史数据")
            except Exception:
                msg = f"数据下载失败，触发异常：\n{traceback.format_exc()}"
                print(msg)

    if  bars and len(bars) > 0:
        df = pd.DataFrame(
        [
            {
                "datetime": s.datetime,
                "close": s.close_price,
                "low": s.low_price,
                "high": s.high_price,
                "open": s.open_price,
                "volume": s.volume,
            }
            for s in bars
        ]
        )

        df.set_index(["datetime"], inplace=True)
        print(df.head(3))
        print(df.to_csv(f'{symbol}.csv', columns=['open','high','low','close','volume']))